import 'dart:io';
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

class DartIoPage extends StatefulWidget {
  DartIoPage({Key? key}) : super(key: key);

  @override
  _DartIoPageState createState() => _DartIoPageState();
}

class _DartIoPageState extends State<DartIoPage> {
  int _counter = 0;

  @override
  void initState() {
    super.initState();
    _readCounter().then(
      (value) {
        setState(
          () {
            _counter = value;
          },
        );
      },
    );
  }

  Future<File> _getLocalFile() async {
    String dir = (await getApplicationDocumentsDirectory()).path;
    return File('$dir/counter.txt');
  }

  Future<int> _readCounter() async {
    try {
      File file = await _getLocalFile();
      String contents = await file.readAsString();
      return int.parse(contents);
    } on FileSystemException {
      return 0;
    }
  }

  _incrementCounter() async {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("文件操作"),
      ),
      body: Center(
        child: Text('点击了$_counter次'),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: _incrementCounter,
        tooltip: 'Increment',
      ),
    );
  }
}
